package com.cloud.screen.common.exception;

import com.cloud.screen.common.result.Quokka;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@ControllerAdvice
public class QkGlobalExceptioinHander {
	private static final Logger logger = LoggerFactory.getLogger(QkGlobalExceptioinHander.class);
	private static final int ERROR_CODE = 500;
	
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Quokka resolveException(HttpServletRequest request, HttpServletResponse resp, Object obj,
			Exception e) {
		if (e instanceof java.net.SocketException) {
			return null;
		}
		// 记录请求参数到错误日志中
		StringBuffer paramBuffer = new StringBuffer();
		paramBuffer.append("请求参数: \n");
		Enumeration<String> enu = request.getParameterNames();
		if (enu != null) {
			while (enu.hasMoreElements()) {
				String paramName = enu.nextElement();
				if ("_".equals(paramName))
					continue;
				paramBuffer.append(paramName + ":" + request.getParameter(paramName) + ";");
			}
			;
		}
		logger.error(paramBuffer.toString(), e);

		// 封装异常信息
		Quokka result = new Quokka(false);
		result.setMessage(e.getMessage());
		result.setCode(ERROR_CODE);
		return result;
	}
	
	
	@ExceptionHandler(value = BizException.class)
	@ResponseBody
	public Quokka resolveBizException(HttpServletRequest request, HttpServletResponse resp, Object obj,
			Exception e) {
		// 封装异常信息
		Quokka result = new Quokka(false);
		if (e instanceof BizException) {
			result.setMessage(e.getMessage());
			result.setCode(((BizException) e).getCode());
		}
		return result;
	}
	
	

}
